package com.lcifn.middleware.rpc.transport.invocation;

import com.lcifn.middleware.rpc.transport.command.Command;
import com.lcifn.middleware.rpc.transport.future.InFlightRequest;
import com.lcifn.middleware.rpc.transport.future.ResponseFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 客户端Invocation
 * @author lichao
 * @date 2021/2/1 16:39
 */
@ChannelHandler.Sharable
public class ClientResponseInvocation extends SimpleChannelInboundHandler<Command> {

    private static final Logger logger = LoggerFactory.getLogger(ClientResponseInvocation.class);

    private InFlightRequest inFlightRequest;

    public ClientResponseInvocation(InFlightRequest inFlightRequest) {
        this.inFlightRequest = inFlightRequest;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Command command) throws Exception {
        logger.info("Receive response: {}...", command);
        ResponseFuture future = inFlightRequest.remove(command.getHeader().getRequestId());
        if (future != null) {
            future.getFuture().complete(command);
        } else {
            logger.warn("Drop response: {}", command);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
